<template>
  <div>
    <el-container style="height: 100vh;">
      <!-- 固定侧边栏 -->
      <el-aside :style="{ width: asideWidth, position: 'fixed', top: 0, bottom: 0, backgroundColor: white }">
        <el-header style="color: black; background-color: white; padding: 0 15px;">
          <div style="display: flex; margin-top: 15px;">
            <div style="flex:50%; display: flex; width: 130px;">
              <div style="flex:15%; font-weight: bold">
                <img alt="lala" src="@/assets/boyun.png" style="width:45px;height: 45px;" @click="$router.push('/')">
              </div>
              <div style="flex:85%; font-size: 20px;padding-left: 16px;padding-top: 6px;font-weight: bold">
             博云
                <el-button
                    type="text"
                    style="padding-top: 10px; float: right; color: grey; font-size: 15px;"
                    @click="$router.push('/')"
                >
                  <i class="el-icon-back"></i> 回退
                </el-button>
              </div>
            </div>
          </div>
        </el-header>

        <!-- 搜索和添加按钮 -->
        <div style="padding: 15px;align-content: center;justify-content: center">
          <el-button type="info" plain style="width: 235px;border-radius: 3%; border: none" @click="dialogVisible = true">
            <i class="el-icon-search" style="font-size: medium">搜索</i>
          </el-button>
          <el-button plain style="width: 43px;border-radius: 20%;justify-content: center;align-content: center"  @click="handleAdd" >
            <i class="el-icon-plus"></i>
          </el-button>
        </div>

        <!-- 侧边栏菜单 -->
        <el-menu  class="custom-menu" :collapse="isCollapse" :collapse-transition="false" :default-active="$route.path" active-text-color="black" router style="border: none; background-color: white;">
          <el-menu-item @click="toIndex">
            <i class="el-icon-receiving"></i>
            <span slot="title">首页</span>
          </el-menu-item>

          <!-- 目录菜单，递归显示子目录 -->
          <el-submenu  v-for="item in menuItems" :key="item.id" :index="'category-' + item.id">
            <template slot="title">
              <span>{{ item.name }}</span>
              <i class="el-icon-document-add"  @click="handleAdd"></i>
            </template>

            <!-- 如果目录下有笔记，直接显示笔记 -->
            <el-menu-item v-if="item.notePoList && item.notePoList.length" v-for="note in item.notePoList" :key="note.id" :index="note.id.toString()" @click="handleMenuItemClick(note)">
              <i class="el-icon-document" style="color: #409EFF;"></i>
              {{ note.title }}
              <div class="xxxs"  @click.stop="handleMoreClick(item)">
                <el-dropdown placement="bottom" style="border-radius:50%;width:35px;height: 35px;">
                  <div style="display: flex;align-items: center ;cursor:default;margin-top: 10px">
                    <i class="el-icon-more xxxs" style="cursor:pointer;color: #cccccc; font-size: 15px; margin-right: 10px;"></i>
                  </div>
                  <!-- 下拉栏内容 @click.native  item没有click事件-->
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item @click.native="editAdd(note)">编辑</el-dropdown-item>
                    <el-dropdown-item @click.native="$router.push('/password')">收藏</el-dropdown-item>
                    <el-dropdown-item @click.native="deleteNote(note)">删除</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </div>
            </el-menu-item>

            <!-- 递归处理子目录 -->
            <el-submenu  v-for="subItem in item.categoryPoList" :key="subItem.id" :index="'category-' + subItem.id">
              <template slot="title">
                <i class="el-icon-folder"></i> {{ subItem.name }}
              </template>

              <!-- 处理子目录下的笔记 -->
              <el-menu-item  v-if="subItem.notePoList && subItem.notePoList.length" v-for="subNote in subItem.notePoList" :key="subNote.id" :index="'note-' + subNote.id" @click="handleMenuItemClick(subNote)">
                <i class="el-icon-document" style="color: #409EFF;"></i>
                {{ subNote.title }}
                <div class="xxxs"  @click.stop="handleMoreClick(item)">
                  <el-dropdown placement="bottom" style="border-radius:50%;width:35px;height: 35px;">
                    <div style="display: flex;align-items: center ;cursor:default;margin-top: 10px">
                      <i class="el-icon-more xxxs" style="cursor:pointer;color: #cccccc; font-size: 15px; margin-right: 10px;"></i>
                    </div>
                    <!-- 下拉栏内容 @click.native  item没有click事件-->
                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item  @click.native="editAdd(subNote)">编辑</el-dropdown-item>
                      <el-dropdown-item @click.native="$router.push('/password')">收藏</el-dropdown-item>
                      <el-dropdown-item @click.native="deleteNote(subNote)">删除</el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>
                </div>
              </el-menu-item>

              <!-- 递归调用自身处理更深层次的目录 -->
              <el-submenu v-if="subItem.categoryPoList && subItem.categoryPoList.length" v-for="subSubItem in subItem.categoryPoList" :key="subSubItem.id" :index="'category-' + subSubItem.id">
                <template slot="title">
                  <i class="el-icon-folder"></i> {{ subSubItem.name }}
                  <div class="xxxs"  @click.stop="handleMoreClick(subSubItem)">
                    <el-dropdown placement="bottom" style="border-radius:50%;width:35px;height: 35px;">
                      <div style="display: flex;align-items: center ;cursor:default;margin-top: 10px">
                        <i class="el-icon-more xxxs" style="cursor:pointer;color: #cccccc; font-size: 15px; margin-right: 10px;"></i>
                      </div>
                      <!-- 下拉栏内容 @click.native  item没有click事件-->
                      <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item  >编辑</el-dropdown-item>
                        <el-dropdown-item @click.native="$router.push('/password')">收藏</el-dropdown-item>
                        <el-dropdown-item @click.native="deleteNote(subSubItem)">删除</el-dropdown-item>
                      </el-dropdown-menu>
                    </el-dropdown>
                  </div>
                </template>

                <!-- 递归到最后，如果该目录下有笔记 -->
                <el-menu-item   v-if="subSubItem.notePoList && subSubItem.notePoList.length" v-for="subSubNote in subSubItem.notePoList" :key="subSubNote.id" :index="'note-' + subSubNote.id" @click="handleMenuItemClick(subSubNote)">
                  <i class="el-icon-document" style="color: #409EFF;"></i>
                  {{ subSubNote.title }}
                  <div class="xxxs"  @click.stop="handleMoreClick(item)">
                    <el-dropdown placement="bottom" style="border-radius:50%;width:35px;height: 35px;">
                      <div style="display: flex;align-items: center ;cursor:default;margin-top: 10px">
                        <i class="el-icon-more xxxs" style="cursor:pointer;color: #cccccc; font-size: 15px; margin-right: 10px;"></i>
                      </div>
                      <!-- 下拉栏内容 @click.native  item没有click事件-->
                      <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item @click.native="editAdd(subSubNote)">权限</el-dropdown-item>
                        <el-dropdown-item @click.native="$router.push('/password')">更多设置</el-dropdown-item>
                        <el-dropdown-item @click.native="deleteNote(item)">删除</el-dropdown-item>
                      </el-dropdown-menu>
                    </el-dropdown>
                  </div>
                </el-menu-item>

              </el-submenu>
            </el-submenu>
          </el-submenu>
        </el-menu>
      </el-aside>

      <!-- 主内容区 -->
      <el-main :style="{ marginLeft: asideWidth, flex: '83%',padding: '0 15px' }">
        <router-view @update:user="updateUser"/>
      </el-main>
    </el-container>

    <!-- 弹窗组件 -->
    <el-dialog class="rounded-dialog" :title="dialogTitle" :visible.sync="dialogVisible" width="40%" :before-close="handleClose">
      <el-input placeholder="搜索内容，或输入 > 唤醒更多" prefix-icon="el-icon-search" v-model="searchQuery" style="width: 100%; margin-bottom: 20px;"></el-input>
      <div>
        <ul>
          <li v-for="item in menuItems" :key="item.id" class="menu-item">
            <a :href="item.index" class="menu-link">
              <i class="el-icon-notebook-2 back-icon" style="color: #409EFF;"></i>
              <span class="menu-text">{{ item.name }}</span>
            </a>
            <i class="el-icon-right jump-icon" style="color: #409EFF;">跳转</i>
          </li>
        </ul>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSearch">搜 索</el-button>
      </span>
    </el-dialog>
    <el-dialog title="添加笔记" top="0.51vh" modal="true"   :visible.sync="newsFormVisble" width="40%" height="'auto'"  @close="closeDialog":close-on-click-modal="false">
      <el-form :model="form" label-width="80px" style="padding-right: 20px" :rules="rules" ref="formRef">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="标题"></el-input>
        </el-form-item>
        <el-form-item label="简介" prop="descr">
          <el-input v-model="form.descr" placeholder="简介"></el-input>
        </el-form-item>
        <el-form-item label="内容"  prop="content">
          <div id="add-editor"></div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="newsFormVisble = false,handleCancel()">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="编辑笔记" top="0.51vh" modal="true"   :visible.sync="editFormVisble" width="40%" height="'auto'"  @close="closeDialog":close-on-click-modal="false">
      <el-form :model="editForm" label-width="80px" style="padding-right: 20px" :rules="rules" ref="formRef">
        <el-form-item label="标题" prop="title">
          <el-input v-model="editForm.title" placeholder="标题"  ></el-input>
        </el-form-item>
        <el-form-item label="简介" prop="descr">
          <el-input v-model="editForm.descr" placeholder="简介"> </el-input>
        </el-form-item>
        <el-form-item label="内容"  prop="content">
          <div  id="edit-editor"></div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editFormVisble = false">取 消</el-button>
        <el-button type="primary" @click="edit">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>
<script>
import E from "wangeditor"
import hljs from 'highlight.js'
import { Loading } from 'element-ui';
export default {
  name: "HomeView",
  data() {
    return {
      form: {
        title: '',
        descr: '',
        content: '',
        userId:'',
        categoryBy:""
      },
      editForm: {
        title: '',
        descr: '',
        content: '',
        userId:'',
        categoryBy:""
      },
      newsFormVisble:false,
      editFormVisble:false,
      user: JSON.parse(localStorage.getItem('honey-user') || '{}'),
      dialogVisible: false,
      editDialogVisible:false,
      searchQuery: '',
      isCollapse: false,
      asideWidth: '17%',
      menuItems: [], // 保存目录数据
      name: '', // 当前显示的目录名称
      info: {
        id: '',
        userId: ''
      },
      noteList: [],
      editor: null,
      deleteInfo:{
        id:'',
        userId:''
      },
    };
  },
  mounted() {
    // 只有当路由路径与目标路径不同的时候才执行请求
    if (this.$route.path !== '/note') {
      this.sendPostRequest();
    }
  },
  created() {
    // 从路由查询参数中获取数据
    this.info.id = this.$route.query.id;
    if (this.info.id !== localStorage.getItem('infoId')){
      this.sendPostRequest();
      return;
    }
    // 从 localStorage 恢复数据
    const storedNoteName = localStorage.getItem('noteName');
    const storedTitleName= localStorage.getItem('titleName');
     const storedMenuItems = localStorage.getItem('menuItems');

    if (storedNoteName) {
      this.name = storedTitleName; // 恢复笔记名称
    }
    if (storedMenuItems) {
      this.menuItems = JSON.parse(storedMenuItems); // 恢复菜单数据
    } else {
      this.sendPostRequest(); // 如果没有菜单数据，则请求
    }


  },
  methods: {
    toIndex() {
      const currentId = this.$route.query.id; // Current id in the route
      const storedId = localStorage.getItem('noteListId');
      if (storedId !== currentId) { // Only replace if ids are different
        this.$router.replace({
          path: '/noteList',
          query: { id: storedId }
        });
      }
    },
    deleteNote(item) {
      this.deleteInfo.id=item.id
      this.deleteInfo.userId=this.user.userId
      this.$request.post('/notes/delete',this.deleteInfo).then(res=>{
        if (res.code==="200"){
          this.$message.success("删除成功")
          this.sendPostRequest()
        }else {
          this.$message.error("删除失败")
        }
      })
    },
    edit(){
      this.$refs.formRef.validate((valid) => {
       console.log(valid)
        if (valid) {
          //获取编辑框的内容
          let content = this.editor.txt.html()   // 设置html
          this.editForm.content=content
          this.$request({
            url: '/notes/edit',
            method: 'POST',
            data: this.editForm
          }).then(res => {
            if (res.code === "200") {//表示成功保存
              this.$message.success('编辑成功')
              this.editFormVisble = false;
            } else {
              this.$message.error(res.msg)//弹出错误信息
            }
          })
        }
      })

    },
    save() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          //获取编辑框的内容
          let content = this.editor.txt.html()   // 设置html
          this.form.content=content
          this.form.userId=this.user.userId
          this.form.categoryBy='5'
          this.$request({
            url: '/notes/addNote',
            method: 'POST',
            data: this.form
          }).then(res => {
            if (res.code === "200") {//表示成功保存
              this.$message.success('保存成功')
              this.newsFormVisble = false;
              this.editFormVisble = false;
            } else {
              this.$message.error(res.msg)//弹出错误信息
            }
          })
        }
      })
    },
    editAdd(item) {
      this.editFormVisble = true; //打开弹窗
      this.editForm = JSON.parse(JSON.stringify(item))
      this.editForm.categoryBy=item.categoryBy
      this.editForm.id=item.id
      this.editForm.userId=this.user.userId
      this.setRichText(2)
      //设置延时
      setTimeout(()=>{
        this.editor.txt.html(item.content)   // 获取内容
      },0)
    },
    handleAdd() {//新增数据
      this.form = {}//新增数据的时候清空
      this.newsFormVisble = true; //打开弹窗
      this.setRichText(1)
    },
    setRichText(id){
      this.$nextTick(()=>{
        if (id===1){
          this.editor = new E(`#add-editor`)
        }else {
          this.editor = new E(`#edit-editor`)
        }
        this.editor.highlight = hljs
        this.editor.config.placeholder = '请输入内容...'
        this.editor.config.uploadImgServer = this.$baseUrl + '/file/upload'
        this.editor.config.uploadFileName = 'file'
        this.editor.config.uploadImgHeaders = {
            'x-token': this.user.token
        }
        this.editor.config.timeout= 5000*2
        this.editor.config.uploadImgParams={
          type:'img'
        }
        this.editor.config.height = 600; // 设置高度
        //  this.editor.config.width = 300; // 设置宽度
        // 自定义图片上传逻辑

        this.editor.config.uploadImgMaxSize = 40 * 1024 * 1024 // 10M
        this.editor.config.uploadVideoServer = this.$baseUrl + '/file/upload'
        this.editor.config.uploadVideoName = 'file'
        // this.editor.config.uploadVideoHeaders = {
        //     token: this.user.token
        // }
        this.editor.config.uploadVideoParams={
          type:'video'
        }
        this.editor.config.maxFileSize= 200 * 1024 * 1024, // 200M
            this.editor.config.allowedFileTypes=['mp4','MP4'],
            this.editor.create()  // 创建
      })
    },
    closeDialog(){
      // 销毁编辑器
      this.editor.destroy()
      this.editor = null
    },
    handleMenuItemClick(item) {
      // 路由跳转时传递参数，并替换当前路由
      this.$router.replace({
        path: '/note',
        query: { id: item.id, name: item.title ,content:item.content,descr:item.descr}
      });
      // 将数据存储到 localStorage
      localStorage.setItem('infoId', this.info.id);},
    handleSearch() {
      console.log('搜索关键词:', this.searchQuery);
      this.dialogVisible = false;
    },

    sendPostRequest() {
      this.info.userId = this.user.userId;
      this.info.id = this.$route.query.id;
      localStorage.setItem('infoId', this.info.id);
      this.$request.post('/notes/queryCategoryAndNoteName', this.info).then(res => {
        if (res.code === "200") {
          this.menuItems = res.data;  // 更新菜单项
          this.noteList = res.data[0]; // 假设加载第一个菜单项的数据
          localStorage.setItem('menuItems', JSON.stringify(res.data));  // 保存菜单数据
          this.$router.push({
            path: '/noteList',
            query: {
              id: this.info.id,
              name: this.name
            }
          });
        } else {
          this.$message.error("菜单加载失败");
        }
      }).catch(error => {
        console.error("请求失败", error);
        this.$message.error("请求失败，请稍后重试");
      });
    },
    updateUser(user) {
      this.user = JSON.parse(JSON.stringify(user)); // 深拷贝
    }
  }
};
</script>

<style scoped>
.xxxs {
  position: absolute; /* 设置绝对定位 */
  right: 10px; /* 距离容器右侧10px */
  top: 50%; /* 垂直居中 */
  transform: translateY(-50%); /* 垂直居中 */
}
.custom-menu .el-menu-item, .custom-menu .el-submenu__title, .custom-submenu .el-menu-item {
  height: 36px; /* 减小菜单项的高度 */
  line-height: 36px; /* 确保文本垂直居中 */
  padding: 0 20px; /* 减小内边距 */
  font-size: 14px; /* 减小字体大小 */
}
/* 隐藏所有子菜单标题中的上下箭头 */
.custom-menu .el-submenu__title .el-icon-arrow-down,
.custom-menu .el-submenu__title .el-icon-arrow-up {
  display: none !important;
}

/* 隐藏子菜单的箭头 */
.custom-menu .el-submenu__title i {
  display: none !important;
}


.menu-item {
  margin: 15px 0; /* 上下间距 */
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 20px; /* 内边距使内容与边框有空间 */
  border-radius: 4px; /* 圆角效果 */
  transition: background-color 0.3s ease; /* 平滑过渡 */
  position: relative; /* 确保相对定位 */
}

.menu-link {
  text-decoration: none;
  color: inherit;
  display: flex;
  align-items: center;
  font-size: 15px; /* 调整字体大小 */
}

.menu-link .el-icon-notebook-2 {
  font-size: 18px; /* 调整图标大小 */
  margin-right: 8px; /* 图标与文本之间的间距 */
}

.menu-text {
  font-size: 15px; /* 确保文本和链接的字体大小一致 */
}

.jump-icon {
  font-size: 15px; /* 跳转图标的大小 */
  margin-left: auto; /* 将图标推到最右边 */
  padding-right: 10px; /* 右侧内边距 */
  visibility: hidden; /* 默认隐藏 */
  transition: visibility 0.3s, opacity 0.3s; /* 平滑过渡 */
}

/* 设置悬停时的背景颜色和显示跳转图标 */
.menu-item:hover {
  background-color: #eff0f0; /* 悬停时的背景颜色 */
}

.menu-item:hover .jump-icon {
  visibility: visible; /* 显示跳转图标 */
  opacity: 1; /* 确保完全可见 */
}

.rounded-dialog {
  border-radius: 12px; /* 设置圆角大小 */
}

.rounded-dialog .el-dialog__header,
.rounded-dialog .el-dialog__body,
.rounded-dialog .el-dialog__footer {
  border-radius: 12px; /* 确保对话框的所有部分都有圆角 */
}

.custom-menu .el-menu-item,
.custom-menu .el-submenu__title {
  margin: 1px 0; /* 减小上下间距 */
  padding: 0px 0px; /* 调整内边距 */
  border-radius: 6px; /* 设置初始圆角 */
}

.custom-menu .el-menu-item:hover,
.custom-menu .el-submenu__title:hover {
  background-color: #ecf5ff; /* 悬停时的背景颜色 */
  border-radius: 12px; /* 悬停时更大的圆角 */
}

.custom-menu .el-menu-item.is-active {
  background-color: #e4f3ff; /* 激活状态的背景颜色 */
  border-radius: 15px; /* 激活状态更大的圆角 */
}

.custom-menu .el-menu-item i,
.custom-menu .el-submenu__title i {
  font-size: 18px; /* 调整图标大小 */
  margin-right: 8px; /* 图标与文本之间的间距 */
}

.custom-menu .el-menu-item span,
.custom-menu .el-submenu__title span {
  font-size: 13px; /* 调整文本大小 */
}

#edit-editor {
  height: 630px; /* 确保编辑器有高度 */
}
#add-editor {
  height: 630px; /* 确保编辑器有高度 */
}

</style>

